package com.macro.mall.service.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.macro.mall.common.config.XhsApiConfig;
import com.macro.mall.common.exception.XhsApiException;
import com.macro.mall.dto.XhsTokenResponse;
import com.macro.mall.model.request.AuthTokenRequest;
import com.macro.mall.model.response.AuthTokenResponse;
import com.macro.mall.model.response.PreAuthCodeResponse;
import com.macro.mall.service.XhsLoginService;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import okhttp3.HttpUrl;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import org.mybatis.logging.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.logging.Logger;

@Service
@Slf4j
public class XhsLoginServiceImpl implements XhsLoginService {



    private static final String CACHE_KEY = "xhs_access_token";
    private static final long REFRESH_BUFFER = 300_000; // 5分钟缓冲时间

    @Value("${xhs.app-id}")
    private String appId;

    @Value("${xhs.access-token}")
    private String secret;

    @Resource
    private XhsApiConfig apiConfig;


    @Resource
    private OkHttpClient httpClient;
    @Resource
    private  ObjectMapper objectMapper;

    private static final MediaType JSON = MediaType.get("application/json; charset=utf-8");
    @Override
//    @Cacheable(value = "xhsToken", unless = "#result == null")
    public String getValidToken() throws XhsApiException {
        return refreshTokenInternal();
    }

//    @Scheduled(fixedRate = 7200 * 1000 - 300000) // 2小时 - 5分钟
    @Override
    public void refreshToken() throws XhsApiException {
        refreshTokenInternal();
    }


    private synchronized String refreshTokenInternal() throws XhsApiException {
        try {
            // 构建JSON请求体
            String json = String.format("{\"appid\":\"%s\",\"secret\":\"%s\"}", appId, secret);
            RequestBody body = RequestBody.create(json, JSON);

            Request request = new Request.Builder()
//                    .url("https://miniapp.xiaohongshu.com/api/rmp/token")
                    .url(apiConfig.getBaseUrl() + "/api/rmp/token")
                    .post(body)
                    .addHeader("Content-Type", "application/json")
                    .build();

            try (Response response = httpClient.newCall(request).execute()) {
                if (!response.isSuccessful()) {
                    throw new XhsApiException("HTTP错误: " + response.code());
                }

                // 打印原始响应调试
                String rawResponse = response.body().string();
                System.out.println("Raw Response: " + rawResponse);

                XhsTokenResponse tokenResponse = XhsTokenResponse.parseFromJson(rawResponse);

                if (tokenResponse == null) {
                    throw new XhsApiException("响应解析失败");
                }

                if (!tokenResponse.isSuccess()) {
                    throw new XhsApiException("小红书API错误: " + tokenResponse.getMsg());
                }

                return tokenResponse.getData().getAccess_token();
            }
        } catch (IOException e) {
            log.error("Token刷新失败", e);
            throw new XhsApiException("API请求异常", e);
        }
    }
















    @Override
    public AuthTokenResponse getAuthToken(AuthTokenRequest request) throws Exception {
        try {
            // 1. 获取API地址
            String apiUrl = apiConfig.getBaseUrl() + "/api/rmp/tp/auth/token";

            // 2. 获取有效access_token
            String accessToken = this.getValidToken();
            if (!StringUtils.hasText(accessToken)) {
                log.error("获取access_token失败");

            }

            // 3. 构建请求URL
            HttpUrl url = HttpUrl.parse(apiUrl).newBuilder()
                    .addQueryParameter("app_id", apiConfig.getAppId())
                    .addQueryParameter("access_token", accessToken)
                    .build();

            // 4. 构建请求体
            String jsonBody = objectMapper.writeValueAsString(request);
            RequestBody body = RequestBody.create(jsonBody, MediaType.parse("application/json"));

            // 5. 构建HTTP请求
            Request httpRequest = new Request.Builder()
                    .url(url)
                    .post(body)
                    .addHeader("Content-Type", "application/json")
                    .build();

            // 6. 执行请求
            try (Response response = httpClient.newCall(httpRequest).execute()) {
                if (!response.isSuccessful()) {
                    String errorMsg = String.format("获取授权调用凭证失败，状态码: %d", response.code());
                    log.error(errorMsg);

                }

                // 7. 解析响应
                String responseBody = response.body().string();
                AuthTokenResponse authResponse = objectMapper.readValue(responseBody, AuthTokenResponse.class);

                if (authResponse == null || !authResponse.getSuccess() ||
                        authResponse.getData() == null) {
                    log.error("授权调用凭证响应数据解析失败");

                }

                // 8. 更新当前token和过期时间
//                currentAuthToken = authResponse.getData().getAuthAccessToken();
//                tokenExpireTime = System.currentTimeMillis() + (authResponse.getData().getExpireIn() * 1000L);

                log.info("成功获取授权调用凭证，有效期: {}秒", authResponse.getData().getExpireIn());
                return authResponse;
            }
        } catch (IOException e) {
            log.error("获取授权调用凭证网络异常", e);
            throw new Exception("获取授权调用凭证网络异常", e);
        }
    }
















    @Override
    public PreAuthCodeResponse getPreAuthCode() throws Exception {
        try {
            // 1. 获取API地址
            String apiUrl = apiConfig.getBaseUrl() + "/api/rmp/tp/pre_auth_code";

            // 2. 获取有效access_token
            String accessToken = this.getValidToken();
            if (!StringUtils.hasText(accessToken)) {
                log.error("获取access_token失败");

            }

            // 3. 构建请求URL
            HttpUrl url = HttpUrl.parse(apiUrl).newBuilder()
                    .addQueryParameter("app_id", apiConfig.getAppId())
                    .addQueryParameter("access_token", accessToken)
                    .build();

            // 4. 构建HTTP请求
            Request httpRequest = new Request.Builder()
                    .url(url)
                    .post(RequestBody.create("", MediaType.parse("application/json")))
                    .addHeader("Content-Type", "application/json")
                    .build();

            // 5. 执行请求
            try (Response response = httpClient.newCall(httpRequest).execute()) {
                if (!response.isSuccessful()) {
                    String errorMsg = String.format("获取预授权码失败，状态码: %d", response.code());
                    log.error(errorMsg);

                }

                // 6. 解析响应
                String responseBody = response.body().string();
                PreAuthCodeResponse preAuthResponse = objectMapper.readValue(responseBody, PreAuthCodeResponse.class);

                if (preAuthResponse == null || !preAuthResponse.getSuccess() ||
                        preAuthResponse.getData() == null) {
                    log.error("预授权码响应数据解析失败");
                    throw new XhsApiException("预授权码响应数据解析失败");
                }

                // 7. 记录获取结果
                log.info("成功获取预授权码，有效期: {}秒", preAuthResponse.getData().getExpireIn());
                return preAuthResponse;
            }
        } catch (IOException e) {
            log.error("获取预授权码网络异常", e);
            throw new Exception("获取预授权码网络异常", e);
        }
    }
}
